package App.Controller;

import App.Model.Chat.GroupResponse;
import App.Model.Tecent.TecentIMConfig;
import App.Model.Upload.UploadFileResponse;
import App.Model.WeChat.WeChatRequest;
import App.Model.WeChat.WeChatResponse;
import App.Repository.ProjectRepository;
import App.Service.AccountService;
import App.Service.DemoService;
import App.Service.TecentIMService;
import App.Service.XingeService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;
import java.util.Date;

/**
 * Created by xw on 2018/12/3.
 * this is the demo controller
 */

@RestController
@RequestMapping("/api/demo/")
public class DemoController extends BaseController {

    @Autowired
    private XingeService _xinge;

    @Autowired
    private DemoService _demo;

    @Autowired
    private ProjectRepository _projectRepository;


    @Resource
    private AccountService _accountService;

    @Autowired
    private RestTemplate restTemplate;
    private String rootUrl = "https://console.tim.qq.com/v4/group_open_http_svc/";
    private String createGroup = "create_group";
    private String _method = "get_appid_group_list";


    @RequestMapping("wechat")
    public ResponseEntity<?> testWeChat(@RequestBody(required = false) WeChatRequest _request) {

        String _result = "";
        WeChatResponse _response = new WeChatResponse();
        _response.setUrl("");
        try {
            String _code = "oArvSlySuBeSWnGOsbf-cvrROmdxdkkEQ_zSPWkJ1LE&state";
            _result = _xinge.testWeChat(_request.getCode());
            _response.setUrl(_result);

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        HttpHeaders headers = new HttpHeaders();
        headers.add("Access-Control-Allow-Origin", "*");

        return ResponseEntity.status(200).headers(headers).body(_response);


        // return new ResponseEntity(_response, HttpStatus.OK).getHeaders().add();


    }


    @RequestMapping("wjxlogin")
    public ResponseEntity<?> testGrammer() {

        WeChatResponse _response = new WeChatResponse();
        try {

            String _appid = "677732";
            String _appkey = "ed28d9a58bb14f1889c40f7e01edca32";
            String _subuser = "sanxian01";

            //_subuser="sxlshw";
            String _mobile = "15827117879";
            String _email = "";
            String _roleid = "2";

            Date _newDate = new Date();
            String _ts = Long.toString(_newDate.getTime());

            String _signText = _appid + _appkey + _subuser + _mobile + _email + _roleid + _ts;
            String _sign = org.apache.commons.codec.digest.DigestUtils.sha1Hex(_signText);
            String _url = String.format("https://sanxian.wjx.cn/zunxiang/login.aspx?appid=%s&subuser=%s&mobile=%s&email=%s&roleId=%s&ts=%s&sign=%s"
                    , _appid, _subuser, _mobile, _email, _roleid, _ts, _sign);

            _response.setUrl(_url);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return ResponseEntity.status(200).body(_response);

    }


    @RequestMapping("push")
    public String xingePushTest() {
        String _result = "";

        try {
            System.out.println("step 1");
            List<String> _accounts = new ArrayList<>();
            String _title = "法力任务提醒";
            String _content = " ios push message test:account list:11";
            _accounts.add("53");
            _accounts.add("100");
            // _accounts.add("11");


            //  _result = _xinge.pushMessageAndroid(_accounts,_title,_content);

            // _result = _xinge.pushMessage(_accounts,_title,_content);
            System.out.println("step 2");

        } catch (Exception ex) {

            ex.printStackTrace();
        }
        return _result;
    }


    @RequestMapping(value = "upload_new")
    @ResponseBody
    public ResponseEntity<?> uploadFile(@RequestParam(value = "file", required = true) MultipartFile file) throws IOException {

        UploadFileResponse _response = new UploadFileResponse();

        String _filePath = "/data/approot/uploads/";
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith("win")) {
            _filePath = "E:\\uploads\\";
        }

        String _fileid = UUID.randomUUID().toString();
        String _oldFileName = file.getOriginalFilename();
        String _fileSuffix = FilenameUtils.getExtension(_oldFileName);
        String _fileName = _fileid + "." + _fileSuffix;


        byte[] bytes = file.getBytes();
        File fileToSave = new File(_filePath + _fileName);
        FileCopyUtils.copy(bytes, fileToSave);

        _response.setFileid(_fileid);
        _response.setNewfilename(_fileName);
        _response.setOldfilename(_oldFileName);


        return new ResponseEntity(_response, HttpStatus.OK);


    }

    @RequestMapping(value = "/importExcel")
    public String importExcel(@RequestParam MultipartFile file, @RequestParam String userId) {
        System.out.println(file.getOriginalFilename());
        return "";
    }

    @RequestMapping(value = "upload_old")
    public ResponseEntity<?> upload(@RequestParam(value = "file", required = true) MultipartFile file) {

        UploadFileResponse _response = new UploadFileResponse();

        if (!file.isEmpty()) {
            try {

                // 这里只是简单例子，文件直接输出到项目路径下。
                // 实际项目中，文件需要输出到指定位置，需要在增加代码处理。
                // 还有关于文件格式限制、文件大小限制，详见：中配置。

                //TODO: 限制文件大小

                String _filePath = "/data/approot/uploads/";
                String os = System.getProperty("os.name");
                if (os.toLowerCase().startsWith("win")) {
                    _filePath = "E:\\uploads\\";
                }
                String _fileid = UUID.randomUUID().toString();
                String _oldFileName = file.getOriginalFilename();
                String _fileSuffix = FilenameUtils.getExtension(_oldFileName);
                String _fileName = _fileid + "." + _fileSuffix;

               /* BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(_filePath + _fileName)));
                out.write(file.getBytes());
                out.flush();
                out.close();
*/

                byte[] bytes = file.getBytes();
                File fileToSave = new File(_filePath + _fileName);
                FileCopyUtils.copy(bytes, fileToSave);
                //   return fileToSave.getAbsolutePath();


                _response.setFileid(_fileid);
                _response.setNewfilename(_fileName);
                _response.setOldfilename(_oldFileName);


            } catch (FileNotFoundException e) {
                e.printStackTrace();
                // return "上传失败," + e.getMessage();
            } catch (IOException e) {
                e.printStackTrace();
                // return "上传失败," + e.getMessage();
            }
            // return "上传成功";
        } else {
            //  return "上传失败，因为文件是空的.";
        }

        return new ResponseEntity(_response, HttpStatus.OK);
    }

    @RequestMapping(value = "/upload/batch")
    public String batchUpload(HttpServletRequest request) {

        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename())));
                    stream.write(bytes);
                    stream.close();
                } catch (Exception e) {
                    stream = null;
                    return "You failed to upload " + i + " => " + e.getMessage();
                }
            } else {
                return "You failed to upload " + i + " because the file was empty.";
            }
        }
        return "upload successful";
    }

    @RequestMapping("/upload2")
    public String singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
            return "redirect:uploadStatus";
        }

        try {
            // Get the file and save it somewhere
            byte[] bytes = file.getBytes();
            // Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            //   Files.write(path, bytes);
            redirectAttributes.addFlashAttribute("message", "You successfully uploaded '" + file.getOriginalFilename() + "'");

        } catch (IOException e) {
            e.printStackTrace();
        }

        return "redirect:/uploadStatus";
    }

    @RequestMapping(value = "upload3")
    public String importExcel(@RequestParam MultipartFile file) {

        return file.getOriginalFilename();

    }


    @RequestMapping("new")
    public String newTest() {

        _demo.findUsersNoPage();

        return "ok";
    }

    @RequestMapping("random")
    public String random() {
        double rr = Math.random();

        Random rand = new Random(99999999);
        int aa = rand.nextInt();

        int a1 = 100;
        int a2 = 100;
        if (a1 == a2) {
            System.out.println("is equal 1");
        } else {
            System.out.println("is not equal 1");
        }

        String a = "123";
        String b = "123";
        if (a == b) {
            System.out.println("is equal");
        } else {
            System.out.println("is not  equal");
        }
        return Integer.toString(aa);
    }

    @RequestMapping("send")
    public String demo() {

        String strJson = "";

        try {

            int userid = userId();
            int sdkid = 1400166247;
            int random = 99999999;
            String sig = "eJxFkNFOgzAUht*FW4yeFrpWEy*2YQRDNW7O6G4a0hbWbOsa2hmm8d1FZPHyfF-*nPOfr*ilXF5WzhklqiCSVkU3EUQXA9adM60WVR1022NECMEAZ-uhW28OthcYEEE4AfiXRmkbTG3*giP0puknfreaF88ZFEnxtpFJAccZnWeObuy0Lo1a7OKuRuA8NOpT5djfT4vm-XXpVoyd2LXd5-qKPORZ-Jhzb2MnY7TezZ74uuRU8m57e16mtmLo9XtACoAmE5zSUQaz10OjNGGMMpaOvJLycLRBhJPTwyO*fwArolSe";
            double rr = Math.random();
            System.out.println(rr);

            String url = String.format("%s%s?usersig=%s&identifier=%s&sdkappid=%s&random=%s&contenttype=json", rootUrl, _method, sig, userid, sdkid, random);

            System.out.println(url);

            JSONObject postData = new JSONObject();
            postData.put("GroupType", "Private");


            System.out.println(postData.toString());
            ResponseEntity<String> o = restTemplate.postForEntity(url, postData, String.class);

            GroupResponse aa = JSON.parseObject(o.getBody(), GroupResponse.class);

            String ok = aa.getActionStatus();
            System.out.println("isok:" + ok);

            return ok;


            //strJson=JSON.toJSONString(o);
            // strJson = o.getBody();

            //ResponseEntity<String>

            //  restTemplate.postForObject()

        } catch (Exception ex) {

            ex.printStackTrace();
        }

        return strJson;
    }


    /**
     * 获取im所有群组
     */
    @Resource
    private TecentIMService tecentIMService;

    @RequestMapping("/groups")
    public Object groups() {
//        String groupid, String groupName, String groupIntroduction, int userid
        String groupId = "1e889dd0-583a-4439-8a99-aa985da79182";
//        String groupName = "云通讯续费";
//        String groupIntroduction = "云通讯续费";
//        String groupId = "264200ad-04ad-4028-b421-0a0137cfc88c";
//        String groupName = "软件续费";
//        String groupIntroduction = "软件续费";
//        int userid = 131;
//        List<Integer> integers = Arrays.asList(119);
//        tecentIMService.createIMGroup(groupId,groupName,groupIntroduction,userid);
//        tecentIMService.addIMGroupMember(groupId,integers,userid);

        List<String> GroupIdList = new ArrayList<>();
        GroupIdList.add(groupId);
        return tecentIMService.queryGroups(GroupIdList);
    }

}
